<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增考场安排')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-examSchedule-add">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">场次编号：</label>
                <div class="col-sm-4">
                    <input name="examId" class="form-control" type="text" required>
                </div>
                <label class="col-sm-2 control-label is-required">名称：</label>
                <div class="col-sm-4">
                    <input name="name" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">年级：</label>
                <div class="col-sm-4">
                    <input id="gradeName" name="gradeName"  type="hidden" >
                    <select class='form-control selectpicker' data-live-search="true" id='gradeId' name='gradeId' required>
                    </select>
                </div>
                <label class="col-sm-2 control-label is-required">学期：</label>
                <div class="col-sm-4">
                    <select class='form-control selectpicker' data-live-search="true" name="semester" id="semester" th:with="type=${@dict.getType('sc_term_type')}" required>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">总人数：</label>
                <div class="col-sm-4">
                    <input name="total" class="form-control" type="number" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">考试开始日期：</label>
                <div class="col-sm-4">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input name="examTime" class="form-control" placeholder="yyyy-MM-dd" type="text">
                    </div>
                </div>

                <label class="col-sm-2 control-label">考试结束日期：</label>
                <div class="col-sm-4">
                    <div class="input-group date">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        <input name="examEnd" class="form-control" placeholder="yyyy-MM-dd" type="text">
                    </div>
                </div>
            </div>
            <div class="form-group">
<!--                <button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal">添加考场</button>-->
                <button type="button" class="btn btn-info btn-xs" onclick="selectFixed()">选中固定考场</button>
                <div id="add_select">
                    <table id="room_table" class="table table-bordered"></table>
                </div>
            </div>
        </form>
    </div>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true" aria-labelledby="myModalLabel">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;
                    </button>
                    <h4 class="modal-title" id="myModalLabel">
                        添加考场
                    </h4>
                </div>
                <div class="modal-body form-horizontal">

                    <div class="form-group">
                        <label class="col-sm-3 control-label is-required">考场编号：</label>
                        <div class="col-sm-8">
                            <input name="roomId" id="roomId" class="form-control" type="text" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label is-required">考场位置：</label>
                        <div class="col-sm-8">
                            <input name="location" id="location" class="form-control" type="text" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label is-required">容纳人数：</label>
                        <div class="col-sm-8">
                            <input name="numbers" id="numbers" class="form-control" type="number" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label is-required">排序：</label>
                        <div class="col-sm-8">
                            <input name="orderNum" id="orderNum" class="form-control" type="number" required>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveRoom()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-select-js" />
    <script type="text/javascript">
        var prefix = ctx + "school/examSchedule";
        $("#form-examSchedule-add").validate({
            focusCleanup: true
        });

        var selectRommId = []

        function submitHandler() {
            $("#gradeName").val($("#gradeId option:selected").text());
            if ($.validate.form()) {
                var answerListArray = $("#room_table").bootstrapTable('getData');
                var data = $('#form-examSchedule-add').serializeJSON();
                //var answerList = JSON.stringify( answerListArray );
                if(answerListArray != null){
                    for (let i = 0; i < answerListArray.length; i++) {
                        data["list["+i+"].rid"]=answerListArray[i].id;
                        data["list["+i+"].rRid"]=answerListArray[i].rid;
                        data["list["+i+"].roomId"]=answerListArray[i].roomId;
                        data["list["+i+"].location"]=answerListArray[i].location;
                        data["list["+i+"].numbers"]=answerListArray[i].numbers;
                        data["list["+i+"].orderNum"]=answerListArray[i].orderNum;
                    }
                }
                $.operate.save(prefix + "/add", data);
            }
        }

        $("input[name='examTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
        $("input[name='examEnd']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(document).ready(function(){

            $.ajax({
                type: "post",
                url:ctx + "school/grade/getGradeList",
                async:false,
                dataType: "json",
                success: function(res){
                    if (null != res) {
                        var html = '';
                        Object.keys(res).forEach(function(key){
                            html += '<option value="' + res[key].id + '" data-tokens="'+ res[key].gradeName+'">' + res[key].gradeName+ '</option>';
                        });
                        $("#gradeId").html(html);
                        //必须加，刷新select
                        $("#gradeId").selectpicker('refresh');
                    }
                }
            });
        });

        $(function() {
            $("#room_table").bootstrapTable({
                uniqueId: "id",
                columns: [
                    {
                        field: 'id',
                        title: 'Id',
                        visible: false
                    },
                    {
                        field: 'rRid',
                        title: 'rId',
                        visible: false
                    },
                    {
                        field: 'roomId',
                        title: '考场编号'
                    },
                    {
                        field: 'location',
                        title: '考场位置'
                    },
                    {
                        field: 'numbers',
                        title: '容纳人数'
                    },
                    {
                        field: 'orderNum',
                        title: '排序'
                    }, {
                    field: 'opt',
                    title: '操作'
                }]
            })
        });

        function add() {
            var table = $("#room_select").find('table');
            if(table.length == 0){
                innitTable();
            }else {
                insertRow(table)
            }

        }
        
        function selectFixed() {
            var url = ctx + "school/roomInfo/getRoomList";
            var options = {
                title: '选择固定考场',
                width: "700",
                url: url,
                callBack: doSubmit
            };
            $.modal.openOptions(options);
        }

        function doSubmit(index, layero){
            var table = layero.find("iframe")[0].contentWindow.$.table;
            var ids = table.selectColumns("id");
            if(ids.length == 0){
                $.modal.alertWarning("请选择一条记录");
                return;
            }
            var datas = $("#room_table").bootstrapTable("getOptions").data;
            var index1 = datas.length;
            var rids = table.selectColumns("id");
            var roomIds = table.selectColumns("roomId");
            var locations = table.selectColumns("location");
            var personNumbers = table.selectColumns("personNumber");
            for(let i=0;i<ids.length;i++){
                var randomId = 100 + ~~(Math.random() * 100);
                var rid = roomIds[i];
                if(rIdExit(rid)==0){
                    $("#room_table").bootstrapTable('insertRow', {
                        index: index1+i, // 你想插入到哪，0表示第一行
                        row: {
                            id:randomId,
                            rid:rids[i],
                            roomId: rid,
                            location: locations[i],
                            numbers: personNumbers[i],
                            orderNum:  1,
                            opt: '<button type="button" class="btn btn-danger btn-xs" onclick="removeRowByUniqueId('+randomId+')"><i class="fa fa-remove"></i>删除</button>'
                        }
                    });
                    selectRommId.push(rid);
                }

            }
            layer.close(index);
        }

        function  rIdExit(rId) {
            var ex = 0;
            var len = selectRommId.length
            for(var im = 0;im<len;im++){
                var sId = selectRommId[im];
                if(sId == rId){
                    ex = 1;
                    break;
                }
            }
            return ex;
        }




        /* 删除行ID值为1的数据 */
        function removeRowByUniqueId(id){
            var rows = $('#room_table').bootstrapTable('getRowByUniqueId',id);//行的数据
            var index = selectRommId.indexOf(rows.roomId);
            selectRommId.splice(index, 1)
            $("#room_table").bootstrapTable('removeByUniqueId', id)
        }

        /* 新增表格行 */
        function insertRow(obj){
            var index = $(obj).bootstrapTable("getOptions").data.length;
            $(obj).bootstrapTable('insertRow', {
                index: index, // 你想插入到哪，0表示第一行
                row: {
                    id:1,
                    roomId: '',
                    location: '',
                    numbers: '',
                    orderNum:  '',
                    opt: '<button type="button" class="btn btn-primary btn-xs" onclick="removeRowByUniqueId(1)">删除</button>'
                }
            })
        }

        function saveRoom() {

            let rId = $("#roomId").val();
            let locationI = $('#location').val();
            var datas = $("#room_table").bootstrapTable("getOptions").data;
            console.log(datas);
            let rk = '',rl='';
            for(let i=0; i< datas.length;i++){
                let row = datas[i]
                if(row.roomId === rId){
                    rk = rId;
                }
                if(row.location == locationI){
                    rl = locationI;
                }
            }
            if(rk.length>0){
                $.modal.alertWarning("已经添加过该考场："+rk);
                return;
            }
            if(rl.length>0){
                $.modal.alertWarning("已经添加过该教室："+rl);
                return;
            }
            var index = datas.length;
            var randomId = 100 + ~~(Math.random() * 100)
            $("#room_table").bootstrapTable('insertRow', {
                index: index, // 你想插入到哪，0表示第一行
                row: {
                    id:randomId,
                    roomId: $("#roomId").val(),
                    location: $('#location').val(),
                    numbers: $("#numbers").val(),
                    orderNum:  $("#orderNum").val(),
                    opt: '<button type="button" class="btn btn-danger btn-xs" onclick="removeRowByUniqueId('+randomId+')"><i class="fa fa-remove"></i>删除</button>'
                }
            })
            $('#myModal').modal('hide')
        }
    </script>
</body>
</html>